package cn.yogehaoren.badfox.spring.common;

import cn.yogehaoren.badfox.annotation.Fox;
import cn.yogehaoren.badfox.annotation.DownloadInterceptor;
import cn.yogehaoren.badfox.annotation.Interceptor;

import cn.yogehaoren.badfox.core.BadFoxDownloadInterceptor;
import cn.yogehaoren.badfox.core.BadFoxInterceptor;
import cn.yogehaoren.badfox.def.BaseBadFox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;


public class BadFoxBeanPostProcessor implements BeanPostProcessor {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class beanClass = bean.getClass();
        Fox fox = (Fox) beanClass.getAnnotation(Fox.class);
        if (fox != null) {
            if (BaseBadFox.class.isAssignableFrom(beanClass)) {
                BadFoxCache.addCrawler(beanClass);
            } else {
                logger.error("Crawler={} not extends {@link cn.yogehaoren.def.BadFoxCrawler}", beanClass.getName());
            }
        }
        Interceptor interceptor = (Interceptor) beanClass.getAnnotation(Interceptor.class);
        if (interceptor != null) {
            if (BadFoxInterceptor.class.isAssignableFrom(beanClass)) {
                BadFoxCache.addInterceptor((BadFoxInterceptor) bean);
            } else {
                logger.error("find class = {}, has @Interceptor but not implement cn.yogehaoren.core.BadFoxInterceptor", beanClass.getName());
            }
        }
        DownloadInterceptor downloadInterceptor = (DownloadInterceptor) beanClass.getAnnotation(DownloadInterceptor.class);
        if(downloadInterceptor!=null){

            if (BadFoxDownloadInterceptor.class.isAssignableFrom(beanClass)) {
                BadFoxCache.addDownloadInterceptor((BadFoxDownloadInterceptor) bean);
            } else {
                logger.error("find class = {}, has @Interceptor but not implement cn.yogehaoren.core.BadFoxDownloadInterceptor", beanClass.getName());
            }

        }
        return bean;
    }
}
